﻿using System.Windows.Controls;
using nRoute.Components.Composition;
using nRoute.ViewServices.Contracts;
#if !SILVERLIGHT
using System.Linq;
using System.IO;
using Microsoft.Win32;
#endif

namespace nRoute.ViewServices.Services
{
    [MapViewService(typeof(IOpenFileViewService), OpenFileViewService.SERVICE_NAME,
         InitializationMode = InitializationMode.OnDemand, Lifetime = ViewServiceLifetime.PerInstance)]
    public class OpenFileViewService 
		 : IOpenFileViewService
    {
        private const string SERVICE_NAME = "nRouteOpenFileViewService"; 
        private const string ALL_FILES_FILTER = "All Files (*.*)|*.*";

        private string _filter = ALL_FILES_FILTER;  // by default
        private int _filterIndex = 1;               // by default, this is important
        
#region IOpenFileViewService Members

        public string Filter
        {
            get { return _filter; }
            set { _filter = value; }
        }

        public int FilterIndex 
        {
            get { return _filterIndex; }
            set { _filterIndex = value; }
        }

        public bool Multiselect { get; set; }

        public OpenFileResponse OpenFile()
        {
            var _openFileDialog = new OpenFileDialog
                                      {
                                          Filter = Filter,
                                          FilterIndex = FilterIndex,
                                          Multiselect = Multiselect
                                      };

            // we open and send back the result
            var _result = _openFileDialog.ShowDialog();

#if SILVERLIGHT
            return !_result.GetValueOrDefault(false) ? new OpenFileResponse(true) :
                new OpenFileResponse(_openFileDialog.File, _openFileDialog.Files);
#else
            return !_result.GetValueOrDefault(false) ? new OpenFileResponse(true) :
                new OpenFileResponse(
                    new FileInfo(_openFileDialog.FileName),
                    from f in _openFileDialog.FileNames 
                    select new FileInfo(f));
#endif

        }

#endregion

    }

}

